const md5 = require('md5');
const { jwtSign } = require('../../util/jwt');
let User  = require('../../models/system/user')
// 注册
const register =  async (req, res, next) => {
	try{
    //获取请求体用户名
    const { username } = req.body
    const user = await User.findOne({ username });
    if(user){
      return res.json({
        code: 1001,
        msg: '用户名已存在'
      })
    }
		await User.create({
			username: req.body.username,
			password: req.body.password
		})
		res.json({
			code: 200,
			msg: '注册成功'
		})
	}catch(error){
    next(error)
	}
}
// 登录
const login =  async (req, res, next) => {
  try {
    //获取请求体账户 密码
    const {username, password} = req.body
    const user = await User.findOne({ username });
    // 用户不存在
    if(!user){
      res.json({
        code: 1001,
        msg: '用户不存在'
      })
    }
    // md5 加密对比
    if(md5(password) !== user.password){
      return res.json({
        code: 1001,
        msg: '密码不正确'
      })
    }
    req.session.username =  user.username;
    res.cookie('my','express',{'signed': true})
    let token = jwtSign({
      username: user.username,
      id: user._id
    });
    let userinfo = {
      username: user.username,
      id: user._id,
      token: `${token}`
    }
    res.json({
      code: 200, 
      msg: '登录成功', 
      data: {
        userinfo
      } 
    })
  } catch (error) {
    next(error)
  }
}

// 注册
const logout =  async (req, res, next) => {
  try {
    // 第二种退出登录
    req.session.destroy();
    // 回调到首页
    res.json({
      code: 200,
      msg: '退出成功'
    })
  } catch (error) {
    next(error)
  }
}
module.exports = {
  register,
  login,
  logout
}